/*
 * Copyright 2011 The Rusted Roof, LLC.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package org.proteusframework.platformservice.persistence.c14n;

import org.proteusframework.core.api.model.INamespace;
import org.proteusframework.core.base.Namespace;
import org.proteusframework.platformservice.persistence.messagebean.DataType;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Tacoma Four
 */
final class NamespaceArrayC14NHandler extends AbstractC14NHandler
{
    @Override
    public Object fromC14N(byte[] bytes)
    {
        List<INamespace> nsList = new ArrayList<INamespace>();
        DataInputStream nsDis = new DataInputStream(new ByteArrayInputStream(bytes));

        try
        {
            while (true)
            {
                nsList.add(Namespace.fromCanonical(nsDis.readUTF()));
            }
        } catch (EOFException ignore)
        {

        } catch (IOException e)
        {
            e.printStackTrace();
        }

        INamespace[] nsValues = new INamespace[nsList.size()];
        return nsList.toArray(nsValues);
    }

    @Override
    public byte[] toC14N(Object object)
    {
        byte[] nsBytes = new byte[0];

        INamespace[] nsValues = (INamespace[]) object;
        ByteArrayOutputStream nsBaos = new ByteArrayOutputStream();
        DataOutputStream nsDos = new DataOutputStream(nsBaos);

        String nsHeader = PACKED_BLOB_PREFIX + DataType.NamespaceArrayType.ordinal() + PACKED_BLOB_SUFFIX;
        byte[] nsHeaderBytes = nsHeader.getBytes();
        try
        {
            nsDos.write(nsHeaderBytes, 0, nsHeaderBytes.length);
            for (INamespace curValue : nsValues)
            {
                nsDos.writeUTF(Namespace.toCanonical(curValue, true));
            }

            nsDos.flush();
            nsDos.close();

            nsBytes = nsBaos.toByteArray();
        } catch (IOException e)
        {
            e.printStackTrace();
        }

        return nsBytes;
    }
}
